package com.example.emos.api.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jl
 * @since 2021/1/19 22:05
 */
@Component
@ServerEndpoint("/webSocket/{key}")
@Slf4j
public class WebSocket {

    private Session session;
    private static final ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "key") String key) {
        this.session = session;
        webSocketMap.put(key, this);
        log.info("【websocket消息】有新的连接【{}】, 总数:{}", key, webSocketMap.size());
    }

    @OnClose
    public void onClose(@PathParam(value = "key") String key) {
        webSocketMap.remove(key);
        log.info("【websocket消息】连接断开, 总数:{}", webSocketMap.size());
    }

    @OnMessage
    public void onMessage(String message, @PathParam(value = "key") String key) {
        log.info("【websocket消息】收到客户端【{}】发来的消息:{}", key, message);
    }

    /**
     * 指定用户发送
     */
    public void sendMessage(String message, String key) {
        log.info("【websocket消息】发送指定消息, message={}, key={}", message, key);
        try {
            webSocketMap.get(key).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 群发
     */
    public void sendMessage(String message) {
        log.info("【websocket消息】广播消息, message={}", message);
        for (String key : webSocketMap.keySet()) {
            try {
                webSocketMap.get(key).session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
